package me.zhengjie.common.utils

import cn.hutool.json.JSONObject
import com.alibaba.fastjson.JSON
import me.zhengjie.common.exception.BadRequestException
import me.zhengjie.common.utils.enums.DataScopeEnum
import org.springframework.http.HttpStatus
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails

/**
 * 获取当前登录的用户
 * @author Kuki Wu
 * @date 2019-01-17
 */
object SecurityUtils {
    val userDetails: UserDetails
        get() {
            val userDetails: UserDetails
            userDetails = try {
                SecurityContextHolder.getContext().authentication.principal as UserDetails
            } catch (e: Exception) {
                throw BadRequestException(
                    HttpStatus.UNAUTHORIZED,
                    "登录状态过期"
                )
            }
            return userDetails
        }

    val username: String
        /**
         * 获取系统用户名称
         * @return 系统用户名称
         */
        get() {
            val obj: Any = userDetails
            return JSONObject(obj).get("username", String::class.java)
        }

    val userId: Long
        /**
         * 获取系统用户id
         * @return 系统用户id
         */
        get() {
            val obj: Any = userDetails
            return JSONObject(obj).get("id", Long::class.java)
        }

    /**
     * 获取当前用户的数据权限
     * @return /
     */
    fun getCurrentUserDataScope(): List<Long>? {
        val userDetails: UserDetails = SecurityUtils.userDetails
        // 将 Java 对象转换为 JSONObject 对象
        val jsonObject = JSON.toJSON(userDetails) as com.alibaba.fastjson.JSONObject
        val jsonArray = jsonObject.getJSONArray("dataScopes")
        return JSON.parseArray(jsonArray.toJSONString(), Long::class.java)
    }

    /**
     * 获取数据权限级别
     * @return 级别
     */
    fun getDataScopeType(): String {
        val dataScopes: List<Long> = getCurrentUserDataScope()!!;
        return if (dataScopes.size != 0) {
            ""
        } else DataScopeEnum.ALL.value
    }
}